<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>iterator遍历器</title>
</head>
<body>
  <script>
    /**
     * 1. 数组的values方法
     * 2. 数组的keys方法
     * 3. 手动实现Array的values方法
    */

    // 1. 数组的values方法
    const arr = [1, 2];
    const valueIterator = arr.values();
    console.log(valueIterator.next());
    console.log(valueIterator.next());
    console.log(valueIterator.next());

    // 2. 数组的keys方法
    const keyIterator = arr.keys();
    console.log(keyIterator.next());
    console.log(keyIterator.next());
    console.log(keyIterator.next());

    // 3. 手动实现Array的values方法
    Array.prototype.values = function () {
      let i = 0;
      const length = this.length;
      const that = this; // 在外层定义this，在next()直接使用this指向的是next函数
      return {
        next () {
          return {
            value: that[i],
            done: i++ >= length
          }
        }
      }
    }
    const valuesArr = [1, 2, 34];
    const defineValuesIterator = valuesArr.values();
    console.log('values', defineValuesIterator.next());
    console.log('values', defineValuesIterator.next());
    console.log('values', defineValuesIterator.next());
    console.log('values', defineValuesIterator.next());
  </script>
</body>
</html>